import { routerRedux } from 'dva/router';
import { fakeAccountLogin, getUserMenu } from '../services/api';
import { delAuthority, setAuthority } from '../utils/authority';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      console.log('触发', payload);
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(fakeAccountLogin, payload);
      const token = {
        token: response,
      };
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.code === 0) {
        setAuthority(JSON.stringify(token))
        yield put(routerRedux.push('/'));
        const menusData = yield call(getUserMenu);
        console.log('menusData', menusData);
        const menusArray = [];
        menusData.data.map(item => (menusArray.push(item.path)));
        console.log(menusArray);
        yield put({
          type: 'user/menus',
          payload: menusArray,
        });
      }
    },
    *logout(_, { put, call }) {
      delAuthority();
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
        },
      });
      yield put(routerRedux.push('/user/login'));
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        submitting: false,
      };
    },
    changeSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },
  },
};
